<template>
    <el-header class="myhead">
        <el-row class="myrow">
            <el-col :span="8" class="fitem">
                <el-icon class="hicon" @click="changeCollapse(!isCollapse)">
                    <DArrowRight v-if="isCollapse" />
                    <DArrowLeft v-else />
                </el-icon>
                <h2 class="title">柳州工学院后台管理系统</h2>

            </el-col>
            <el-col :span="8" class="fitem">
                <marquee behavior="" direction="">
                    <div class="fbox">
                        <h2>笃志勤学，知行合一</h2>
                        <h2>笃志勤学，知行合一</h2>
                        <h2>笃志勤学，知行合一</h2>
                    </div>
                </marquee>
            </el-col>
            <el-col :span="8" class="fitem">
                <div class="info" v-if="(userInfo && roleList.length > 0)">

                    <el-dropdown @command="handleCommand">
                        <span class="el-name">
                            {{ userInfo.username }}
                            <el-icon class="el-icon--right">
                                <arrow-down />
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="home">首页</el-dropdown-item>
                                <el-dropdown-item command="mine">个人中心</el-dropdown-item>
                                <el-dropdown-item command="advise">意见</el-dropdown-item>
                                <el-dropdown-item command="anno">公告</el-dropdown-item>
                                <el-dropdown-item command="grade">成绩</el-dropdown-item>
                                <el-dropdown-item divided command="changepass">修改密码</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>

                    <div v-if="roleList.find((item) => item.value == userInfo.role)">
                        <el-tag class="m10" effect="dark"
                            :color="roleList.find((item) => item.value == userInfo.role).color">
                            {{ roleList.find((item) => item.value == userInfo.role).label }}
                        </el-tag>
                    </div>

                    <MyAvatar></MyAvatar>

                    <el-tooltip effect="dark" content="注销登录" placement="bottom">
                        <el-button @click="logoutAction" class="m10" type="danger" :icon="Delete" circle />
                    </el-tooltip>

                </div>
            </el-col>
        </el-row>


        <el-dialog v-model="show" title="修改密码" width="30%" :before-close="handleClose">
            <el-form ref="formRef" :model="form" status-icon :rules="rules" label-width="120px" class="myform">
                <el-form-item label="旧密码" prop="oldpass">
                    <el-input :prefix-icon="Lock" clearable v-model="form.oldpass" type="password" show-password
                        placeholder="请输入旧密码" autocomplete="off" />
                </el-form-item>
                <el-form-item label="新密码" prop="newpass">
                    <el-input @input="checkpass" :prefix-icon="Lock" clearable v-model="form.newpass" type="password"
                        show-password placeholder="请输入新密码" autocomplete="off" />
                </el-form-item>
                <el-form-item label="确认新密码" prop="dbnewpass">
                    <el-input :prefix-icon="Lock" clearable v-model="form.dbnewpass" type="password" show-password
                        placeholder="请输入确认新密码" autocomplete="off" />
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="info" @click="handleClose">取消</el-button>
                    <el-button type="danger" @click="submitForm(formRef)">
                        确认修改
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </el-header>
</template>

<script lang="ts" setup >
import { useStore } from '../../store';
import { toRefs, ref, reactive } from 'vue'
import { formRefType, userInfoFace } from '../../utils/types';
import { ArrowLeftBold, ArrowRightBold, DArrowLeft, DArrowRight, ArrowDown, Delete, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { reg } from '../../utils/validate';
import { useFormHook } from '../../hooks/useFormHook';
import { ShowError } from '../../utils/message';
import { Http } from '../../api/api'
import MyAvatar from './MyAvatar.vue'

interface PassTypes {
    oldpass?: String,
    newpass?: String | any,
    dbnewpass?: String | any,
}
const store = useStore()
const router = useRouter()
const { setUserInfo, changeCollapse, } = store;
const { userInfo, roleList, isCollapse } = toRefs(store)
const show = ref<boolean>(false)
const formRef = ref<formRefType | any>()
const form = reactive<PassTypes>({

})

const submitForm = (formEl: formRefType) => {
    if (!formEl) return;

    formEl.validate(async (valid: boolean) => {
        if (valid) {
            console.log(userInfo)
            if (form.oldpass != userInfo.value.password) {
                ShowError('旧密码不正确')
            } else {
                if (form.oldpass == form.newpass) {
                    ShowError('新密码不能跟原始密码一样')
                } else {
                    let res = await Http.changeuserinfo({
                        password: form.newpass,
                    }) as unknown as any;
                    if (res.code == 200) {
                        router.replace('/login')
                        sessionStorage.removeItem('token')
                    }
                }
            }
        } else {
            ShowError('请输入有效的密码')
        }
    })
}

const checkpass = () => {
    if (reg.pwd.test(form.newpass) && reg.pwd.test(form.dbnewpass)) {
        formRef.value.validateField("dbnewpass", () => null)
    }
}

const checkPassCommon = (rule: any, value: any, callback: any) => {
    if (reg.pwd.test(form.newpass)) {
        if (value != form.newpass) {
            callback(new Error("两次密码不匹配"))
        } else {
            callback()
        }
    } else {

        formRef.value.validateField("newpass", () => null)
    }
}
const rules = reactive<FormRules>({
    oldpass: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        {
            pattern: reg.pwd,
            message: '请输入6-16位数字加字母的密码'
        }
    ],
    newpass: [
        { required: true, message: '新密码不能为空', trigger: 'blur' },
        {
            pattern: reg.pwd,
            message: '请输入6-16位数字加字母的密码'
        }
    ],
    dbnewpass: [
        { required: true, message: '确认密码不能为空', trigger: 'blur' },
        {
            pattern: reg.pwd,
            message: '请输入6-16位数字加字母的密码'
        },
        {
            validator: checkPassCommon,
        }
    ]
})



const handleClose = () => {
    show.value = false;
}

const handleCommand = (command: string) => {
    console.log(command)
    if (command == 'changepass') {

        show.value = true;
    } else {
        router.push({ name: command })
    }
}


const logoutAction = () => {
    ElMessageBox.confirm(
        '你确定要退出登录吗?',
        '友情提示',
        {
            confirmButtonText: '确定退出',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {

            sessionStorage.removeItem('token')
            setUserInfo(null)
            router.replace('/login')
        })
        .catch(() => {

        })
}
</script>

<style lang="scss" scoped>
.myhead {
    border-bottom: 1px solid #ddd;
    background: #ccc;

    .myrow {
        height: 100%;
    }

    .fitem {
        display: flex;
        align-items: center;
        height: 100%;
    }

    .title {
        font-size: 22px;
        color: #f50;
        line-height: 1;
    }

    .hicon {
        color: #f50;
        cursor: pointer;

    }

    .fbox {
        display: flex;
        padding: 0 20px;

        h2 {
            margin: 0 20px;
            color: dodgerblue;

        }
    }

    .info {
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 100%;
    }

    .el-name {
        display: flex;
        font-size: 20px;
        color: #000;
        cursor: pointer;
    }

    .m10 {
        margin-left: 10px;
    }
}
</style>